import React, {Fragment} from "react";
import {Menu, Icon, Layout} from 'antd';
import {withRouter, Link} from 'react-router-dom';
import '../../style.less';
import {getMenu} from '../../service/api';
const SubMenu = Menu.SubMenu;
const {Sider} = Layout;

let getMenus = function (menuArr) {
    return menuArr.map(item => {
        if (item.children) {
            return (
                <SubMenu key={item.path} title={<span><Icon type={item.icon}/><span>{item.name}</span></span>}>
                    {getMenus(item.children)}
                </SubMenu>
            )
        }
        return (
            <Menu.Item key={item.path}>{<Link to={item.path}>{item.icon ?
                <Icon type={item.icon}/> : ''}<span>{item.name}</span></Link>}
            </Menu.Item>
        )
    })
}


class MainMenu extends React.Component {
    state = {
        collapsed: false,

    }

    toggleCollapsed = () => {
        this.setState({
            collapsed: !this.state.collapsed,
        });
    }

    componentDidMount(){
        let self = this;
        let getDoc = self.props.location.pathname === "/"?"":"/"+self.props.location.pathname.match(/([^\/]+)/g)[0];
        if(sessionStorage.getItem("menu")){
            self.setState({
                menu: JSON.parse(sessionStorage.getItem("menu")),
                current: self.props.location.pathname,
                openKeys: getDoc
            })
        }else{
            getMenu().then(function (data) {
                self.setState({
                    menu: data.data,
                    current: self.props.location.pathname,
                    openKeys: getDoc
                })
                sessionStorage.setItem("menu",JSON.stringify(data.data))
            })
        }

    }

    render() {

        return (
            <Sider width={246} theme="light" className="sider" collapsed={this.state.collapsed}>
                {/*<Button onClick={this.toggleCollapsed} style={{marginBottom: 16}}>*/}
                {this.state.menu?<Fragment>
                <div className="textCenter">
                    <Icon onClick={this.toggleCollapsed} className="toggleMenu" type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'}/>
                </div>
                {/*</Button>*/}
                <Menu
                    defaultSelectedKeys={[this.state.current]}
                    defaultOpenKeys={[this.state.openKeys]}
                    mode="inline"
                    theme="dark"
                    inlineCollapsed={this.state.collapsed}
                >
                    {getMenus(this.state.menu)}
                </Menu></Fragment>: true}

            </Sider>
        );
    }
}

export default withRouter(MainMenu);